package com.xinhe.cn.cpbox.common;

import lombok.Data;

import java.util.HashMap;
import java.util.Map;

/**
 * @author yekai
 * @date 2020/6/15 09:53
 */
@Data
public class Result {
    private Boolean success;
    private Integer code;
    private String message;
    private Map<String, Object> data = new HashMap<>();

    private Result() {
    }

    /**
     * 通用返回成功
     *
     * @return Result对象
     */
    public static Result ok() {
        Result result = new Result();
        result.setSuccess(ResultCodeEnum.SUCCESS.getSuccess());
        result.setCode(ResultCodeEnum.SUCCESS.getCode());
        result.setMessage(ResultCodeEnum.SUCCESS.getMessage());
        return result;
    }

    /**
     * 通用返回失败，未知错误
     *
     * @return Result对象
     */
    public static Result error() {
        Result result = new Result();
        result.setSuccess(ResultCodeEnum.UNKNOWN_ERROR.getSuccess());
        result.setCode(ResultCodeEnum.UNKNOWN_ERROR.getCode());
        result.setMessage(ResultCodeEnum.UNKNOWN_ERROR.getMessage());
        return result;
    }

    /**
     * 通用返回失败，参数错误
     *
     * @return Result对象
     */
    public static Result paramError() {
        Result result = new Result();
        result.setSuccess(ResultCodeEnum.PARAM_ERROR.getSuccess());
        result.setCode(ResultCodeEnum.PARAM_ERROR.getCode());
        result.setMessage(ResultCodeEnum.PARAM_ERROR.getMessage());
        return result;
    }

    /**
     * 设置结果，形参为结果枚举
     *
     * @param result 要设置的结果
     * @return 设置完成后的Result对象
     */
    public static Result setResult(ResultCodeEnum result) {
        Result result1 = new Result();
        result1.setSuccess(result.getSuccess());
        result1.setCode(result.getCode());
        result1.setMessage(result.getMessage());
        return result1;
    }

    /**
     * ------------使用链式编程，返回类本身-----------
     **/

    /**
     * 自定义返回数据
     *
     * @param map 要设置的数据
     * @return Result对象
     */
    public Result data(Map<String, Object> map) {
        this.setData(map);
        return this;
    }

    /**
     * 设置单个返回数据
     *
     * @param key   键
     * @param value 值
     * @return Result对象
     */
    public Result data(String key, Object value) {
        this.data.put(key, value);
        return this;
    }

    /**
     * 自定义状态信息
     *
     * @param message 状态信息
     * @return Result对象
     */
    public Result message(String message) {
        this.setMessage(message);
        return this;
    }

    /**
     * 自定义状态码
     *
     * @param code 状态码
     * @return Result对象
     */
    public Result code(Integer code) {
        this.setCode(code);
        return this;
    }

    /**
     * 自定义返回结果
     */
    public Result success(Boolean success) {
        this.setSuccess(success);
        return this;
    }
}
